<?php

namespace api\modules\app\services;

use api\components\Common;
use Yii;
use api\modules\app\models\Unit;
use api\modules\app\models\UnitEvent;
use api\modules\app\models\UnitHistory;
use yii\db\Query;

class HistoryService
{
    /**
     * @param $unitCode 部件标识码
     * @param $type 小类type UnitHistory::TYPE2_INFO_CREATE
     * @param string $userName 更新人
     * @param array $options 可选项
     *
     * @example
     * $options
     *     'user_id' => 5658, //用户id
     *     'state' => UnitService::STATE_UNNORMAL, //部件状态，默认1-正常
     *     'event_id' => 'f915c7b0234b6591ab4829b90075b257', //案件id，类型为event时必填必填
     *     'history_time' => 1626904984 //log时间戳，不填默认当前时间
     * ];
     * HistoryService::log('123456789',UnitHistory::TYPE2_INFO_CREATE,'嵇菁菁', $options);
     *
     * @return bool
     */
    public static function log($unitCode, $type, $userName = '', $options = []) {
        $currentTime = time();

        $unit = Unit::find()->where(['unit_code' => $unitCode])->one();
        if (empty($unit)) {
            return false;
        }
        $type1 = UnitHistory::getType1ByType2($type);
        if (empty($type1)) {
            return false;
        }
        if ($type1 == UnitHistory::TYPE1_EVENT && (!isset($options['event_id']) || empty($options['event_id']))) {
            //案件类型的evnet_id必填
            return false;
        }

        $model = new UnitHistory();
        $model->unit_code = $unitCode;
        $model->state = $unit->state;
        $model->user_name = $userName ? $userName : '';
        $model->type1 = $type1;
        $model->type2 = $type;
        $model->history_time = $currentTime;
        $model->create_time = $currentTime;

        $attrs = ['user_id', 'state', 'event_id', 'history_time'];
        if (!empty($options)) {
            foreach ($attrs as $attr) {
                if (isset($options[$attr]) && !empty($options[$attr])) {
                    $model->$attr = $options[$attr];
                }
            }
        }

        return $model->save();
    }

    public function scanLog($params) {
        $currentTime = time();
        if (!isset($params['type'])) {
            throw new \Exception('参数type不能为空');
        }
        $type2 = $params['type'];
        $type1 = UnitHistory::getType1ByType2($type2);
        if ($type1 != UnitHistory::TYPE1_SCAN) {
            //目前只支持扫码
            throw new \Exception('只支持扫码日志');
        }
        if (empty($type1)) {
            throw new \Exception('参数type不正确');
        }
        $model = new UnitHistory();
        $model->type1 = $type1;
        $model->type2 = $type2;
        $model->history_time = $currentTime;
        $model->create_time = $currentTime;
        return $model->save();
    }

    /**
     * 列表查询
     */
    public function search($params, $count = false) {
        if (!isset($params['unit_code']) || empty($params['unit_code'])) {
            return false;
        }

        $unitCode = $params['unit_code'];
        $db = Yii::$app->get('test_3');
        $query = new Query();
        $query->from('unit_history')->where(['unit_code' => $unitCode]);
        if ($count) {
            return $query->count('*', $db);
        }

        //分页
        Common::constructPage($query, $params);

        $result = $query->orderBy(['history_time' => SORT_DESC])->all($db);
        if (!empty($result)) {
            foreach ($result as &$v) {
                $v['type1'] = UnitHistory::getType1ByKey($v['type1']);
                $v['type2'] = UnitHistory::getType2ByKey($v['type2']);
                $v['event_type'] = '';
                $v['event_desc'] = '';
                if (!empty($v['event_id'])) {
                    $event = UnitEvent::find()->where(['event_id' => $v['event_id']])->one();
                    $v['event_type'] = $event->event_type;
                    $v['event_desc'] = $event->desc;
                }
            }
        }

        return $result;
    }

    public function scanStat($params) {
        if (!isset($params['start_time']) || empty($params['start_time'])) {
            return false;
        }
        if (!isset($params['end_time']) || empty($params['end_time'])) {
            return false;
        }
        if (!isset($params['type']) || empty($params['type'])) {
            return false;
        }
        $startTime = $params['start_time'];
        $endTime = $params['end_time'];
        $type = $params['type'];

        $query = new UnitHistory();
        $result = $query::find()
            ->select(["FROM_UNIXTIME(history_time,'%Y-%m-%d') date",'count(*) as count'])
            ->andWhere(['between','history_time',$startTime,$endTime])
            ->andWhere(['type2'=>$type])
            ->groupBy('date')
            ->asArray()
            ->all();
print_r($result);exit;
    }

}


